#include <TApplication.h>
#include <TCanvas.h>
#include <TColor.h>
#include <TH2D.h>
#include <TFile.h>
#include <iostream>
#include <stdlib.h>
#include <Coefficient.h>
#include <DataReader.h>
using namespace std;

void TCanvas::Closed() {
	Emit("Closed()");

	gApplication->Terminate(0);
}

int main(int argc, char** argv) {
	//	int argcFake = 0;
	//	TApplication* app = new TApplication("App", &argcFake, argv);
	DataReader* dr = new DataReader(argv[1], atoi(argv[2]), true);
	//	Coefficient* coeff = new Coefficient();

	TFile* file = new TFile("output.root", "recreate");
	/*	Double_t r[5] = { 1, 1, 0, 0, 0 };
	 Double_t g[5] = { 0, 1, 1, 1, 0 };
	 Double_t b[5] = { 0, 0, 0, 1, 1 };
	 Double_t stop[5] = { 0, .25, .5, .75, 1 };
	 TColor::CreateGradientColorTable(5, stop, r, g, b, 20);
	 TH2D* lossHisto = new TH2D("lossHisto", "Energy Loss per Photon", 2000, 0, 2000, 101, -0.5, 100.5);*/

	TH1D* pedHisto = new TH1D("Pedestal", "pedHisto", 1025, -0.5, 1024.5);

	double* sum;
	int** data = dr->GetData(0, sum);

	cout << "Event: " << 0 << flush;
	int l = 0;
	while (data && l < 1000) {
		//		double lostEnergy = 0;
		//		double totalEnergy = 0;

		for (int i = 0; i < 2716; i++) {
			if (data[i] == NULL)
				continue;
			double energy = sum[i];

			//			totalEnergy += energy;
			//			if (energy > 0)
			//				if (!coeff->correlates(data[i], 48, atof(argv[3])))
			//					lostEnergy += energy;

			int min = 1024;
			int max = 0;
			for (int j = 0; j < 48; j++) {
				if (data[i][j] > max)
					max = data[i][j];
				if (data[i][j] < min)
					min = data[i][j];
			}
			if (max - min <= 64 && energy > 0)
				pedHisto->Fill(data[i][50]);

			delete[] data[i];
		}

		delete[] data;
		delete[] sum;

		//		if (totalEnergy > 0)
		//			lossHisto->Fill(totalEnergy, lostEnergy / totalEnergy * 100);

		l++;
		data = dr->GetData(l, sum);
		cout << "\rEvent: " << l << flush;
	}
	cout << "\r" << flush;

	//	lossHisto->Draw("cols");
	//	app->Run(true);
	pedHisto->Write();
	file->Close();
	//	delete coeff;
	delete dr;
	//	app->Delete();
	return 0;
}
